<template>
  <el-card class="workstation-card" :class="{ 'expanded': isExpanded, 'fullscreen': isFullscreen }" shadow="hover">
    <template #header>
      <div class="card-header">
        <span>工位: {{ workstation.id }}</span>
        <div>
          <el-tag :type="statusTagType" size="large">{{ statusText }}</el-tag>
          <el-button v-if="isFullscreen" class="close-fullscreen" type="danger" :icon="Close" circle
            @click.stop="exitFullscreen" />
        </div>
      </div>
    </template>

    <div class="card-content">
      <div class="current-job" v-if="currentJob">
        <p><strong>当前加工件:</strong> {{ currentJob.pieceId }}</p>
        <p><strong>产品名称:</strong> {{ currentJob.productName }}</p>
        <p><strong>产品编码:</strong> {{ currentJob.productId }}</p>
        <p><strong>预计时间:</strong> {{ currentJob.estimatedTime }}分钟</p>
        <p><strong>状态:</strong> {{ processingStatus }}</p>
        <p><strong>已加工时间:</strong> {{ formattedElapsedTime }}</p>
        <p><strong>队列预计总耗时:</strong> {{ formattedEstimatedTotalTime }}</p>
      </div>
      <div v-else>
        <p>暂无加工任务</p>
      </div>

      <!-- 时间轴对比组件 -->
      <div class="time-comparison" v-if="isProcessing || isPaused">
        <h4>时间进度对比</h4>
        <div class="timeline-container">
          <div class="timeline">
            <div class="time-marker expected" :style="{ width: expectedProgress + '%' }">
              <span class="time-label">预计: {{ currentJob.estimatedTime }}分钟</span>
            </div>
            <!-- 修改点：添加动态类绑定 -->
            <div class="time-marker actual" :class="actualProgressClass"
              :style="{ width: actualProgressBarWidth + '%' }">
              <span class="time-label">实际: {{ formattedElapsedMinutes }}分钟</span>
            </div>
          </div>
          <div class="time-indicator" :style="{ left: expectedProgress + '%' }"></div>
        </div>
        <div class="time-comparison-result">
          <span v-if="timeComparison > 0" class="time-ahead">
            提前 {{ timeComparison }} 分钟 ({{ timeComparisonPercentage }}%)
          </span>
          <span v-else-if="timeComparison < 0" class="time-behind">
            落后 {{ Math.abs(timeComparison) }} 分钟 ({{ Math.abs(timeComparisonPercentage) }}%)
          </span>
          <span v-else class="time-on-schedule">
            准时完成
          </span>
        </div>
      </div>

      <div class="button-group">
        <el-button type="primary" :icon="VideoPlay" @click.stop="handleStart"
          :disabled="isProcessing || isPaused || !canStart || isLoading" :loading="isStarting">
          <template v-if="isProcessing || isPaused">
            <el-icon class="is-disabled">
              <VideoPlay />
            </el-icon>
            <span>已启动</span>
          </template>
          <template v-else>
            启动
          </template>
        </el-button>

        <el-button v-if="!isPaused" type="warning" :icon="Pause" @click.stop="handlePause"
          :disabled="!isProcessing || isLoading" :loading="isPausing">
          暂停
        </el-button>

        <el-button v-else type="primary" :icon="VideoPlay" @click.stop="handleResume" :disabled="isLoading"
          :loading="isResuming">
          继续
        </el-button>

        <el-button type="success" :icon="CircleCheck" @click.stop="handleFinish"
          :disabled="(!isProcessing && !isPaused) || isLoading" :loading="isFinishing">
          结束
        </el-button>

        <el-button type="info" :icon="isExpanded ? 'ArrowUp' : 'ArrowDown'" @click.stop="toggleExpand"
          v-if="!isFullscreen">
          {{ isExpanded ? '收起' : '展开' }}
        </el-button>

        <el-button type="warning" :icon="FullScreen" @click.stop="toggleFullscreen" v-if="!isFullscreen">
          全屏
        </el-button>
      </div>

      <div class="queue-list" v-if="(isExpanded || isFullscreen) && queue.length > 0">
        <h4>等待队列 (共{{ queue.length }}个):</h4>
        <el-table :data="queue" size="small" style="width: 100%">
          <el-table-column prop="pieceId" label="件号" width="120" />
          <el-table-column prop="productName" label="产品名称" width="150" />
          <el-table-column prop="productId" label="产品编码" width="120" />
          <el-table-column prop="queueNumber" label="队列号" width="80" />
          <el-table-column prop="estimatedTime" label="预计时间(分钟)" width="120" />
          <el-table-column label="状态" width="120">
            <template #default="{ $index }">
              {{ $index === 0 ? processingStatus : '等待中' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220">
            <template #default="{ $index }">
              <div class="action-buttons">
                <el-button type="primary" size="small" @click.stop="moveToFirst($index)"
                  :disabled="$index === 0 || isProcessing || isLoading">
                  置顶
                </el-button>
                <el-button type="success" size="small" @click.stop="moveUp($index)"
                  :disabled="$index === 0 || isProcessing || isLoading">
                  上移
                </el-button>
                <el-button type="warning" size="small" @click.stop="moveDown($index)"
                  :disabled="$index === queue.length - 1 || isProcessing || isLoading">
                  下移
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref, computed, onMounted, watch, onUnmounted } from 'vue'
import dispatchApi from '../api/dispatch'
import { VideoPlay, CircleCheck, FullScreen, Close } from '@element-plus/icons-vue'

import { ElMessage, ElTable, ElTableColumn } from 'element-plus'

const props = defineProps({
  workstation: {
    type: Object,
    required: true
  },
  isExpanded: {
    type: Boolean,
    default: false
  },
  isFullscreen: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['refresh', 'toggle-expand', 'toggle-fullscreen'])

// 状态变量
const queue = ref([])
const isStarting = ref(false)
const isPausing = ref(false)
const isResuming = ref(false)
const isFinishing = ref(false)
const isProcessing = ref(false)
const isPaused = ref(false)
const isLoading = ref(false)

// 计时相关变量
const startTimestamp = ref(null)
const pauseTimestamp = ref(null)
const elapsedTimeBeforePause = ref(0)
const elapsedTime = ref(0)
const timer = ref(null)

// 计算属性
const currentJob = computed(() => queue.value.length > 0 ? queue.value[0] : null)

const totalEstimatedTime = computed(() => {
  return queue.value.reduce((total, item) => total + (item.estimatedTime || 0), 0)
})

const formattedElapsedTime = computed(() => {
  const totalSeconds = Math.floor(elapsedTime.value / 1000)
  const minutes = Math.floor(totalSeconds / 60)
  const seconds = totalSeconds % 60
  return `${minutes}分${seconds.toString().padStart(2, '0')}秒`
})

const formattedElapsedMinutes = computed(() => {
  return (elapsedTime.value / 60000).toFixed(1)
})

const estimatedTotalTime = computed(() => {
  if (!currentJob.value) return totalEstimatedTime.value
  const remainingTime = totalEstimatedTime.value - (elapsedTime.value / 60000)
  return Math.max(0, remainingTime).toFixed(1)
})

const formattedEstimatedTotalTime = computed(() => {
  return `${estimatedTotalTime.value}分钟`
})

const processingStatus = computed(() => {
  if (isProcessing.value) return '加工中'
  if (isPaused.value) return '已暂停'
  return queue.value.length > 0 ? '待启动' : '空闲'
})

const statusTagType = computed(() => {
  if (!currentJob.value) return 'info'
  if (isProcessing.value) return 'success'
  if (isPaused.value) return 'warning'
  return 'primary'
})

const statusText = computed(() => processingStatus.value)

const canStart = computed(() => {
  return queue.value.length > 0 && !isProcessing.value && !isPaused.value
})

// 时间轴对比相关计算属性
const expectedProgress = computed(() => {
  if (!currentJob.value || !currentJob.value.estimatedTime) return 0
  const elapsedMinutes = elapsedTime.value / 60000
  return Math.min(100, (elapsedMinutes / currentJob.value.estimatedTime) * 100)
})

// 修改点：重命名并添加进度条宽度计算（不超过100%）
const actualProgressBarWidth = computed(() => {
  if (!currentJob.value || !currentJob.value.estimatedTime) return 0
  const elapsedMinutes = elapsedTime.value / 60000
  return Math.min(100, (elapsedMinutes / currentJob.value.estimatedTime) * 100)
})

// 新增：实际进度百分比（可超过100%）
const actualProgressPercentage = computed(() => {
  if (!currentJob.value || !currentJob.value.estimatedTime) return 0
  const elapsedMinutes = elapsedTime.value / 60000
  return (elapsedMinutes / currentJob.value.estimatedTime) * 100
})

// 新增：根据进度百分比确定颜色类
const actualProgressClass = computed(() => {
  const percentage = actualProgressPercentage.value;

  if (percentage <= 5) {
    return 'progress-red'; // 0-5%: 红色
  } else if (percentage <= 20) {
    return 'progress-yellow'; // 5-20%: 黄色
  } else if (percentage <= 100) {
    return 'progress-green'; // 20-100%: 绿色
  } else if (percentage <= 120) {
    return 'progress-yellow'; // 100-120%: 黄色
  } else {
    return 'progress-red'; // >120%: 红色
  }
})

const timeComparison = computed(() => {
  if (!currentJob.value || !currentJob.value.estimatedTime) return 0
  const elapsedMinutes = elapsedTime.value / 60000
  return (currentJob.value.estimatedTime - elapsedMinutes).toFixed(1)
})

const timeComparisonPercentage = computed(() => {
  if (!currentJob.value || !currentJob.value.estimatedTime) return 0
  const elapsedMinutes = elapsedTime.value / 60000
  return Math.abs(((currentJob.value.estimatedTime - elapsedMinutes) / currentJob.value.estimatedTime) * 100).toFixed(1)
})

// 方法
const cleanupTimer = () => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
}

const startTimer = () => {
  cleanupTimer()
  startTimestamp.value = Date.now()
  elapsedTimeBeforePause.value = 0
  pauseTimestamp.value = null

  timer.value = setInterval(() => {
    elapsedTime.value = Date.now() - startTimestamp.value
  }, 1000)
}

const pauseTimer = () => {
  cleanupTimer()
  pauseTimestamp.value = Date.now()
  elapsedTimeBeforePause.value = elapsedTime.value
}

const resumeTimer = () => {
  cleanupTimer()
  startTimestamp.value = Date.now() - elapsedTimeBeforePause.value
  pauseTimestamp.value = null

  timer.value = setInterval(() => {
    elapsedTime.value = Date.now() - startTimestamp.value
  }, 1000)
}

const resetTimer = () => {
  cleanupTimer()
  startTimestamp.value = null
  pauseTimestamp.value = null
  elapsedTimeBeforePause.value = 0
  elapsedTime.value = 0
}

const loadQueue = async () => {
  isLoading.value = true
  try {
    const data = await dispatchApi.getDispatchByWorkstation(props.workstation.id)
    queue.value = (data || []).map((item, index) => ({
      ...item,
      displayOrder: index
    }))
    await updateWorkstationStatus()
  } catch (error) {
    console.error('加载工位队列失败:', error)
    ElMessage.error(`加载工位${props.workstation.id}队列失败`)
    queue.value = []
  } finally {
    isLoading.value = false
  }
}

const updateWorkstationStatus = async () => {
  try {
    const status = await dispatchApi.getWorkstationStatus(props.workstation.id)
    isProcessing.value = status === 'PROCESSING'
    isPaused.value = status === 'PAUSED'

    if (isProcessing.value && !timer.value) {
      const progress = await dispatchApi.getProcessingProgress(props.workstation.id)
      elapsedTime.value = progress.elapsedTime * 60000
      startTimestamp.value = Date.now() - elapsedTime.value
      startTimer()
    }
  } catch (error) {
    console.error('获取工位状态失败:', error)
  }
}

const handleStart = async () => {
  if (!canStart.value) return

  isStarting.value = true
  try {
    await dispatchApi.startProcessing(props.workstation.id)
    ElMessage.success('加工已启动')
    isProcessing.value = true
    isPaused.value = false
    startTimer()
    emits('refresh')
  } catch (error) {
    ElMessage.error(error.message || '启动加工失败')
  } finally {
    isStarting.value = false
  }
}

const handlePause = async () => {
  isPausing.value = true
  try {
    await dispatchApi.pauseProcessing(props.workstation.id)
    ElMessage.success('加工已暂停')
    isProcessing.value = false
    isPaused.value = true
    pauseTimer()
    emits('refresh')
  } catch (error) {
    ElMessage.error(error.message || '暂停加工失败')
  } finally {
    isPausing.value = false
  }
}

const handleResume = async () => {
  isResuming.value = true
  try {
    await dispatchApi.resumeProcessing(props.workstation.id)
    ElMessage.success('加工已继续')
    isProcessing.value = true
    isPaused.value = false
    resumeTimer()
    emits('refresh')
  } catch (error) {
    ElMessage.error(error.message || '继续加工失败')
  } finally {
    isResuming.value = false
  }
}

const handleFinish = async () => {
  isFinishing.value = true
  try {
    const actualProcessingTime = elapsedTime.value / 60000
    const result = await dispatchApi.finishProcessing(props.workstation.id, {
      actualTime: actualProcessingTime
    })

    ElMessage.success(result)
    isProcessing.value = false
    isPaused.value = false
    resetTimer()
    await loadQueue()
    emits('refresh')
  } catch (error) {
    ElMessage.error(error.message || '完成加工失败')
  } finally {
    isFinishing.value = false
  }
}

const moveToFirst = (index) => {
  if (index <= 0) return
  const newQueue = [...queue.value]
  const [movedItem] = newQueue.splice(index, 1)
  newQueue.unshift(movedItem)
  queue.value = newQueue.map((item, idx) => ({
    ...item,
    displayOrder: idx
  }))
  ElMessage.success('已置顶')
}

const moveUp = (index) => {
  if (index <= 0) return
  const newQueue = [...queue.value]
    ;[newQueue[index - 1], newQueue[index]] = [newQueue[index], newQueue[index - 1]]
  queue.value = newQueue.map((item, idx) => ({
    ...item,
    displayOrder: idx
  }))
  ElMessage.success('已上移')
}

const moveDown = (index) => {
  if (index >= queue.value.length - 1) return
  const newQueue = [...queue.value]
    ;[newQueue[index], newQueue[index + 1]] = [newQueue[index + 1], newQueue[index]]
  queue.value = newQueue.map((item, idx) => ({
    ...item,
    displayOrder: idx
  }))
  ElMessage.success('已下移')
}

const toggleExpand = () => {
  emits('toggle-expand', props.workstation.id)
}

const toggleFullscreen = () => {
  emits('toggle-fullscreen', props.workstation.id)
}

const exitFullscreen = () => {
  emits('toggle-fullscreen', '')
}

watch(queue, (newQueue) => {
  if (newQueue.length === 0) {
    resetTimer()
  }
})

onMounted(() => {
  loadQueue()
})

onUnmounted(() => {
  cleanupTimer()
})
</script>

<style scoped>
.workstation-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
  position: relative;
  height: auto;
}

.workstation-card.expanded {
  grid-column: span 1;
}

.workstation-card.fullscreen {
  position: fixed;
  top: 20px;
  left: 20px;
  right: 20px;
  bottom: 20px;
  z-index: 1001;
  overflow: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header>div {
  display: flex;
  align-items: center;
  gap: 10px;
}

.close-fullscreen {
  margin-left: 10px;
}

.current-job {
  margin-bottom: 15px;
}

.current-job p {
  margin: 5px 0;
}

/* 时间轴对比样式 */
.time-comparison {
  margin: 20px 0;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.time-comparison h4 {
  margin-bottom: 10px;
  color: #333;
}

.timeline-container {
  position: relative;
  height: 30px;
  margin: 15px 0;
}

.timeline {
  position: relative;
  height: 20px;
  background-color: #e0e0e0;
  border-radius: 10px;
  overflow: hidden;
}

.time-marker {
  position: absolute;
  height: 100%;
  transition: width 0.5s ease;
}

.time-marker.expected {
  background-color: #67c23a;
  opacity: 0.3;
}


/* 新增：进度条颜色类 */
.progress-red {
  background-color: #f56c6c;
  /* 红色 */
}

.progress-yellow {
  background-color: #e6a23c;
  /* 黄色 */
}

.progress-green {
  background-color: #67c23a;
  /* 绿色 */
}

.time-label {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  padding: 0 5px;
  font-size: 12px;
  color: white;
  white-space: nowrap;
}

.time-indicator {
  position: absolute;
  top: 0;
  width: 2px;
  height: 100%;
  background-color: #f56c6c;
}

.time-comparison-result {
  text-align: center;
  font-weight: bold;
  margin-top: 10px;
}

.time-ahead {
  color: #67c23a;
}

.time-behind {
  color: #f56c6c;
}

.time-on-schedule {
  color: #409eff;
}

.button-group {
  margin-top: 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.queue-list {
  margin-top: 15px;
  border-top: 1px solid #eee;
  padding-top: 10px;
}

.queue-list h4 {
  margin-bottom: 10px;
}

.el-button.is-disabled {
  cursor: not-allowed;
  opacity: 0.7;
}

.el-button.is-disabled .el-icon {
  color: var(--el-button-disabled-text-color);
}

.el-button--primary.is-disabled {
  background-color: var(--el-button-disabled-bg-color);
  border-color: var(--el-button-disabled-border-color);
}

.action-buttons {
  display: flex;
  gap: 5px;
  justify-content: center;
}

.action-buttons .el-button {
  flex: 1;
  padding: 8px 10px;
  min-width: 60px;
}

.el-table .cell {
  padding: 8px 0;
}

@media (max-width: 768px) {
  .button-group {
    flex-direction: column;
  }

  .action-buttons {
    flex-direction: column;
  }

  .action-buttons .el-button {
    width: 100%;
  }
}
</style>